using System;
using System.Collections.Generic;
using System.Text;

using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

/*
 * This should use a central background thread or something...
 * It's very slow to resize.
 * 
 * Currently gets about 1MB to each 2KB, very good!
 * 
 * Might also consider something special for text,
 * it may be cheaper to redraw the text than do image
 * compression.  Should expirament with this...
 */

namespace ClientGUI.Modules.Drawing
{
    /// <summary>
    /// Displays a backed bitmap area for efficiency.
    /// </summary>
    public class BitmapDisplayArea : DisplayArea
    {
        //TODO: Make bitmaps updatable.
        //Bitmap my_bitmap;
        Stream compressed;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="b">bitmap to back with</param>
        public BitmapDisplayArea(Bitmap b)
        {
            //my_bitmap = b
            compressed = null;
            BackingBitmap = b;
        }

        private Bitmap GetBitmap()
        {
            compressed.Seek(0, SeekOrigin.Begin);
            return new Bitmap(compressed);
        }

        /// <summary>
        /// Draw the Bitmap onto the given Graphics area
        /// </summary>
        /// <param name="displayArea"></param>
        /// <param name="cr"></param>
        /// <param name="offset"></param>
        public override void Composite(Graphics displayArea, 
                                        Rectangle cr,
                                        Point offset)
        {
            Bitmap b = GetBitmap();
            Rectangle ncr = new Rectangle(cr.X + offset.X,
                                          cr.Y + offset.Y,
                                          cr.Width, cr.Height);
            displayArea.DrawImage(b, offset.X, offset.Y, cr, GraphicsUnit.Pixel);
            b.Dispose();
        }

        /// <summary>
        /// Allow the bitmap to be updated without creating a new DisplayArea
        /// </summary>
        public Bitmap BackingBitmap
        {
            get { return GetBitmap(); }
            set
            {
                if (compressed != null)
                {
                    compressed.Dispose();
                }
                compressed = new MemoryStream();
                value.Save(compressed, ImageFormat.Png) ;
                value.Dispose(); 
            }
        }

        #region IDisposable Members

        /// <summary>
        /// Destroy the bitmap.
        /// </summary>
        public override void Dispose()
        {
            //my_bitmap.Dispose();
            compressed.Dispose();
        }

        #endregion
    }
}
